package com.foolishbird.sdk.api;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.text.TextUtils;

import com.foolishbird.sdk.assist.CallbackObservable;
import com.foolishbird.sdk.assist.Constant;
import com.foolishbird.sdk.content.HNSSNAbsActivity;
import com.foolishbird.sdk.content.HNSSNActivityListener;
import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.core.HttpEngineConduits;

import com.foolishbird.sdk.handler.SimpleAsyncResponseHandler;
import com.foolishbird.sdk.params.ConfigInfoResponseParams;
import com.foolishbird.sdk.params.RoleInfoResponseParams;
import com.foolishbird.sdk.params.bean.ConfigInfo;
import com.foolishbird.sdk.params.bean.Goods;
import com.foolishbird.sdk.params.bean.RoleInfo;
import com.foolishbird.sdk.params.bean.RoleStatus;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.utils.ToolsUtils;
import com.foolishbird.sdk.utils.WL;
import com.foolishbird.sdk.utils.XmlUtils;




public final class FBSDK implements HNSSNActivityListener {

    private static final String TAG = FBSDK.class.getSimpleName();


    private WanSDKConfiguration configuration;
    private HNSSNActivityListener hnssnProxyActivity;

    private volatile RoleInfo mRoleInfo;
    private FBSDK() {
    }

    private volatile static FBSDK instance;

    public static FBSDK getInstance() {
        if (instance == null) {
            synchronized (FBSDK.class) {
                if (instance == null) {
                    instance = new FBSDK();
                }
            }
        }
        return instance;
    }

    private static void destroyInstance() {
        instance = null;
    }

    public RoleInfo getmRoleInfo(){
        return mRoleInfo;
    }




    public synchronized void init(WanSDKConfiguration configuration) {
        if (configuration == null) {
            throw new IllegalArgumentException("WanSDK configuration can not be initialized with null");
        }
        //parse config xml
        if (!XmlUtils.isInitFinished()) {
            XmlUtils.parseConfigValue(configuration.getApplicationContext());
        }

        if (this.configuration == null) {
            this.configuration = configuration;
        } else {
            WL.w(TAG, "Try to initialize WanSDK which had already been initialized before. To re-init WanSDK with new configuration call WanSDK.destroy() at first.");
        }

        String className = XmlUtils.getSdkHNSSNProxyActivityClass();
        Object object = ToolsUtils.createInstance(className);
        if (object instanceof HNSSNActivityListener) {
            hnssnProxyActivity = (HNSSNActivityListener) object;
        }

//        VersionUpdateDownloader.getImpl().init(configuration.getApplicationContext());
//        ActivitiesDownloader.getImpl().init(configuration.getApplicationContext());

        HttpEngineApi.getInstance().init(configuration);

    }

    public synchronized void init(WanSDKConfiguration configuration, final WanSDKCallback callback) {
        init(configuration);

        HttpEngineApi.getInstance().getPlatformConfig(new SimpleAsyncResponseHandler<ConfigInfoResponseParams>(ConfigInfoResponseParams.class) {
            @Override
            public void onAsyncResponseSuccess(int flag, ConfigInfoResponseParams response) {
                if (response != null && response.isSuccess()) {
                    HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
                    conduits.setPlatformConfigInfo(response.getData());
                    if (callback != null) {
                        String message = response.getState().getMsg();
                        callback.onWanSDKResponse(Constant.InitState.INIT_SUCCESS, message, null);
                    }
                } else {
                    HttpEngineApi.getInstance().getEngineConduits().setPlatformConfigInfo(null);
                    if (callback != null) {
                        String message = response != null ? response.getState().getMsg() : "init failed";
                        callback.onWanSDKResponse(Constant.InitState.INIT_FAILED, message, null);
                    }
                }
            }

            @Override
            public void onAsyncException(int flag, Exception ex) {
                super.onAsyncException(flag, ex);
                HttpEngineApi.getInstance().getEngineConduits().setPlatformConfigInfo(null);
                if (callback != null) {
                    callback.onWanSDKException(ex);
                }
            }

            @Override
            public void onAsyncNetworkException(int flag, Exception ex) {
                super.onAsyncNetworkException(flag, ex);
                HttpEngineApi.getInstance().getEngineConduits().setPlatformConfigInfo(null);
                if (callback != null) {
                    callback.onWanSDKException(ex);
                }
            }
        });

    }

    public synchronized void destroy() {
        HttpEngineApi.getInstance().destroy();

        if (this.configuration != null) {
            this.configuration = null;
            WL.d(TAG, "Destroy WanSDK configuration");
        }

        destroyInstance();
    }

    public String getGameId() {
        if (this.configuration != null) {
            return this.configuration.getGameId();
        }
        return "0";
    }

    public String getWeChatAppId() {
        String weChatAppId = "";

//        ConfigInfo configInfo = getPlatformConfigInfo();
//        if (configInfo != null) {
//            weChatAppId = configInfo.getWxAppId();
//        }

        return TextUtils.isEmpty(weChatAppId) ? "unkown" : weChatAppId;
    }


    public String getAppletOriginalId() {
        String originalId = "";

//        ConfigInfo configInfo = getPlatformConfigInfo();
//        if (configInfo != null) {
//            originalId = configInfo.getWxAppletOriginalId();
//        }
//
//        if (TextUtils.isEmpty(originalId)) {
//            originalId = XmlUtils.getAppletOriginalId();
//        }

        return TextUtils.isEmpty(originalId) ? Constant.WECHAT_APPLET_ORIGINAL_ID : originalId;
    }

    public ConfigInfo getPlatformConfigInfo() {
        return HttpEngineApi.getInstance().getEngineConduits().getPlatformConfigInfo();
    }

    public String getTouTiaoChannel(){
        String ttChannle = "";
        SharedPreferences sharedPreferences = configuration.getApplicationContext().getSharedPreferences("wansdksy", Context.MODE_PRIVATE);
        if(sharedPreferences.contains("tt_channel")){
            ttChannle = sharedPreferences.getString("tt_channel","");
        }
        return ttChannle;
    }

//    private String getExitAppAdvertImageUrl(){
//        ConfigInfo configInfo = WanSDK.getInstance().getPlatformConfigInfo();
//        if (configInfo != null) {
//            ExitPopup exitPopup = configInfo.getExitPopup();
//            return exitPopup != null ? exitPopup.getImageUrl() : "";
//        }
//        return "";
//    }

    private void checkInitValue() {
        if (this.configuration == null) {
            throw new IllegalArgumentException("WanSDK configuration is not be initialized.");
        }
    }

    public final boolean isLoggedIn() {
        return HttpEngineApi.getInstance().isLoggedIn();
    }

    public void exitApp(Activity activity) {
//        String imageUrl = getExitAppAdvertImageUrl();
        String imageUrl = "";
        String className = XmlUtils.getSdkFactoryClass();
        Object object = ToolsUtils.createInstance(className);
        if (object instanceof IWanSDKFactory) {
            ((IWanSDKFactory) object).showExitAppDialog(activity, imageUrl);
        } else {
            WL.i(TAG, "exitApp ----> object instance is null.");
        }
    }

    public void login(WanSDKCallback callback) {
        checkInitValue();
        CallbackObservable.getInstance().setLoginCallbackObserver(callback);
        Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_START_LOGIN_ACTIVITY);
        intent.setPackage(configuration.getApplicationContext().getPackageName());
        intent.putExtra(Constant.LocalIntentExtra.INTENT_KEY_LOGIN_INIT_POSITION, Constant.LocalIntentExtra.INTENT_VALUE_LOGIN_INIT_ACCOUNT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        configuration.getApplicationContext().startActivity(intent);
    }

    public void queryPreventAddictionInfo(WanSDKCallback callback) {
        checkInitValue();
        if (callback != null) {
            if (isLoggedIn()) {
                boolean info = HttpEngineApi.getInstance().getEngineConduits().readNeedIdentify();
                String message = "query success.";
                callback.onWanSDKResponse(Constant.GlobleState.GLOBLE_SUCCESS, message, info+"");
            } else {
                String message = "The user is not logged in yet.";
                callback.onWanSDKResponse(Constant.GlobleState.GLOBLE_NOT_LOGGED, message, null);
            }
        }
    }

    public void pay(Goods goods, WanSDKCallback callback) {
        checkInitValue();
        if (isLoggedIn()) {
            boolean needIdentify = HttpEngineApi.getInstance().getEngineConduits().readNeedIdentify();
//            RealNameInfo realNameInfo = HttpEngineApi.getInstance().getEngineConduits().getRealnameInfo();
            if (needIdentify) {
                Intent newIntent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_START_LOGIN_ACTIVITY);
                newIntent.setPackage(configuration.getApplicationContext().getPackageName());
                newIntent.putExtra("goods", goods);
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                configuration.getApplicationContext().startActivity(newIntent);
            } else {
                CallbackObservable.getInstance().setPayCallbackObserver(callback);
                Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_START_PAY_ACTIVITY);
                intent.setPackage(configuration.getApplicationContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("goods", goods);
                configuration.getApplicationContext().startActivity(intent);

            }
        } else {
            WL.w(TAG, "pay ---> The user is not logged in yet.");
            if (callback != null) {
                String message = "The user is not logged in yet.";
                callback.onWanSDKResponse(Constant.PayState.PAY_INIT_NOT_LOGGED, message, null);
            }
        }
    }

    /**
     * 兼容3.0.6之前的老版本SDK
     * @param roleInfo
     * @param callback
     */
    @Deprecated
    public void uploadRoleInfo(RoleInfo roleInfo, final WanSDKCallback callback) {
        uploadRoleInfo(roleInfo, RoleStatus.UNKNOWN, callback);
    }

    public void uploadRoleInfo(RoleInfo roleInfo, RoleStatus status, final WanSDKCallback callback) {
        if(roleInfo == null){
            return;
        }

        checkInitValue();
        if (isLoggedIn()) {
            this.mRoleInfo = roleInfo;
            HttpEngineApi.getInstance().uploadRoleInfo(roleInfo, status, new Callback(callback));
        } else {
            WL.w(TAG, "uploadRoleInfo ---> The user is not logged in yet.");
            if (callback != null) {
                String message = "The user is not logged in yet.";
                callback.onWanSDKResponse(Constant.PayState.PAY_INIT_NOT_LOGGED, message, null);
            }
        }
    }

    public void logout() {
        checkInitValue();
        closeWindow();
        if(this.mRoleInfo != null){
            uploadRoleInfo(this.mRoleInfo.clone(), RoleStatus.LOGOUT, null);
            this.mRoleInfo = null;
        }
        HttpEngineApi.getInstance().logout(null);
//        HttpEngineApi.getInstance().getEngineConduits().saveCurrentLoginUserUID("");
    }

    public void openWindowContent() {
        checkInitValue();
        if (isLoggedIn()) {
            WL.d(TAG, "openWindowContent ---> ");
            HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
//            if (conduits.isOpenWindowContentView() && hnssnProxyActivity instanceof HNSSNAbsActivity) {
//            if (hnssnProxyActivity instanceof HNSSNAbsActivity) {
//                ((HNSSNAbsActivity) hnssnProxyActivity).openFloatWindowContent();
//            }
        } else {
            WL.w(TAG, "openWindow ---> The user is not logged in yet.");
        }
    }

    public void openWindow() {
        checkInitValue();
        if (isLoggedIn()) {
            WL.d(TAG, "openWindow ---> ");
            if (hnssnProxyActivity instanceof HNSSNAbsActivity) {
                ((HNSSNAbsActivity) hnssnProxyActivity).openFloatWindow();
            }
        } else {
            WL.w(TAG, "openWindow ---> The user is not logged in yet.");
        }
    }

    public void closeWindow() {
        checkInitValue();
        if (isLoggedIn()) {
            WL.d(TAG, "closeWindow ---> ");
            if (hnssnProxyActivity instanceof HNSSNAbsActivity) {
                ((HNSSNAbsActivity) hnssnProxyActivity).closeFloatWindow();
            }
        } else {
            WL.w(TAG, "closeWindow ---> The user is not logged in yet.");
        }
    }

    public void startPushWindowMessageTask(RoleInfo roleInfo){
        checkInitValue();
        if (isLoggedIn()) {
            WL.d(TAG, "startPushWindowMessageTask ---> ");

            if (hnssnProxyActivity instanceof HNSSNAbsActivity) {
                ((HNSSNAbsActivity) hnssnProxyActivity).startPushWindowMessageTask(roleInfo);
            }
        } else {
            WL.w(TAG, "startPushWindowMessageTask ---> The user is not logged in yet.");
        }
    }

    @Override
    public void onCreate(Activity activity) {
        WL.w(TAG, "onCreate ---> activity: " + activity.getClass().getName());
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onCreate(activity);
        }
    }

    @Override
    public void onStart() {
        WL.w(TAG, "onStart ---> ");
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onStart();
        }
    }

    @Override
    public void onRestart() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onRestart();
        }
    }

    @Override
    public void onResume() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onResume();
        }
    }

    @Override
    public void onPause() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onPause();
        }
    }

    @Override
    public void onStop() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onStop();
        }
    }

    @Override
    public void onDestroy() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onDestroy();
        }
    }

    @Override
    public void onBackPressed() {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onBackPressed();
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onNewIntent(intent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
        if (hnssnProxyActivity != null) {
            hnssnProxyActivity.onRequestPermissionResult(requestCode, permissions, grantResults);
        }
    }

    private static final class Callback extends SimpleAsyncResponseHandler<RoleInfoResponseParams> {

        private final WanSDKCallback callback;

        Callback(WanSDKCallback callback) {
            super(RoleInfoResponseParams.class);
            this.callback = callback;
        }

        @Override
        public void onAsyncResponseSuccess(int flag, RoleInfoResponseParams response) {
            if (callback != null) {
                if (response != null) {
                    State state = response.getState();
                    callback.onWanSDKResponse(state.getCode(), state.getMsg(), null);
                }
            }
        }

        @Override
        public void onAsyncException(int flag, Exception ex) {
            super.onAsyncException(flag, ex);
            if (callback != null) {
                callback.onWanSDKException(ex);
            }
        }


        @Override
        public void onAsyncNetworkException(int flag, Exception ex) {
            super.onAsyncNetworkException(flag, ex);
            if (callback != null) {
                callback.onWanSDKException(ex);
            }
        }
    }

}
